﻿#include "shared.h"
#include "texture.h"

using namespace std;
using namespace anip;

vector<GLObject*> Shared::_objs;
vector<PreloadedObject*>* Shared::_preloads = nullptr;

PreloadedObject::PreloadedObject()
{
	Shared::addPreloadObject(*this);
}

void PreloadedTexture::load()
{
	_obj = Texture2D::createFromFile(_path);
}

void PreloadedTexture::finalize()
{
	if (_obj == nullptr) return;
	_obj->finalize();
	delete _obj;
}

int Shared::add(GLObject& s)
{
	_objs.push_back(&s);
	return _objs.size() - 1;
}

int Shared::add(initializer_list<GLObject*> objs)
{
	for (auto obj : objs)
	{
		_objs.push_back(obj);
	}
	return _objs.size() - 1;
}

void anip::Shared::addPreloadObject(PreloadedObject& obj)
{
	static vector<PreloadedObject*> preloads; // make sure it's initialized
	_preloads = &preloads;
	preloads.push_back(&obj);
}

void Shared::preloadObjects()
{
	for (auto i : *_preloads)
		i->load();
}

void Shared::finalize()
{
	if (_preloads != nullptr)
		for (auto i : *_preloads)
		{
			i->finalize();
			// Shared doesn't own the PreloadedObject's
		}
	for (auto i : _objs)
	{
		i->finalize();
		delete i;
	}
}